package com.jacky.ws.interceptors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * webSocket 握手拦截器,可用于身份验证
 */
@Component
public class CustomerHandshakeInterceptor implements HandshakeInterceptor {

    private final Logger LOGGER = LoggerFactory.getLogger(CustomerHandshakeInterceptor.class);

    /**
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        LOGGER.info("handshakeInterceptor-beforeHandshake");
        ServletServerHttpRequest req = (ServletServerHttpRequest) request;
        String token = req.getServletRequest().getParameter("token");
        attributes.put("token",token);
        // 在这里拿到token进行权限校验,成功则返回true,校验失败则返回false
        // 但是token从那里获取呢? 要先请求http接口获取? 这有点不理解
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
